﻿using System;
using System.Windows;
using System.Windows.Controls;
using dotNetMagazin201108.PresentationLayer.Views;
using dotNetMagazin201108.BusinessLayer;
using System.Collections.Generic;
using System.Threading;

namespace dotNetMagazin201108.PresentationLayer.Presenter
{
    public class ContactFormPresenter
    {
        private ContactFormView View;
        private CompanyFormPresenter CompanyPresenter;

        public event EventHandler<EventArgs> ContactAdded;
        public event EventHandler<EventArgs> ContactModified;

        public ContactFormPresenter(ContactFormView view)
        {
            View = view;
            CompanyPresenter = new CompanyFormPresenter(new CompanyFormView());
            CompanyPresenter.CompanyCreated += new EventHandler<EventArgs>(CompanyPresenter_CompanyCreated);
            AttachEventHandler();
        }
        private void CompanyPresenter_CompanyCreated(object sender, EventArgs e)
        {
            CompanyListDto company = new CompanyListDto() { Id = CompanyPresenter.NewCompany.Id, Text = CompanyPresenter.NewCompany.Name};
            View.Companies.Items.Add(company);
            View.Companies.SelectedItem = company;
        }
        private void CreateNewCompany_Click(object sender, RoutedEventArgs e)
        {
            CompanyPresenter.ShowView();
        }
        private void AttachEventHandler()
        {
            View.LastName.TextChanged += TextChanged;
            View.FirstName.TextChanged += TextChanged;
            View.Email.TextChanged += TextChanged;
            View.Phone.TextChanged += TextChanged;
            View.Companies.SelectionChanged += SelectionChanged;

            View.Cancel.Click += new RoutedEventHandler(Cancel_Click);
            View.Apply.Click += new RoutedEventHandler(Apply_Click);
            View.CreateNewCompany.Click += new RoutedEventHandler(CreateNewCompany_Click);

            View.Apply.IsEnabled = false;
            View.Cancel.IsEnabled = false;
        }

        private void TextChanged(object sender, TextChangedEventArgs e)
        {
            ToggleButtons();
        }
        private void SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ToggleButtons();
        }
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            View.LastName.Text = View.ContactLastName;
            View.FirstName.Text = View.ContactFirstName;
            View.Phone.Text = View.ContactPhone;
            View.Email.Text = View.ContactEmail;
            for (int i = 0; i < View.Companies.Items.Count; i++)
            {
                if (((CompanyListDto)View.Companies.Items[i]).Id == View.ContactCompanyId)
                {
                    View.Companies.SelectedIndex = i;
                    break;
                }
            }
            ToggleButtons();
        }
        private void Apply_Click(object sender, RoutedEventArgs e)
        {
            Contact contact = GetContactFromUI();
            Thread t = new Thread(delegate()
            {
                ContactRepository contacts = Factory.CreateContactRepository();
                if (contact.Id != 0)
                {
                    contacts.Update(contact);                    
                    View.Dispatcher.BeginInvoke(delegate()
                    {
                        UpdateUI();
                        ToggleButtons(); 
                        if (ContactModified != null) ContactModified(this, EventArgs.Empty);
                    });
                }
                else
                {
                    contacts.Add(contact);
                    if (View.ContactId != 0) throw new Exception("contact id has an unexpected value");
                    View.Dispatcher.BeginInvoke(delegate()
                    {
                        View.ContactId = contact.Id;
                        UpdateUI();
                        ToggleButtons();
                        if (ContactAdded != null) ContactAdded(this, EventArgs.Empty);
                    });
                }
            });
            t.Start();            
        }
        private void UpdateUI()
        {
            View.ContactLastName = View.LastName.Text;
            View.ContactFirstName = View.FirstName.Text;
            View.ContactPhone = View.Phone.Text;
            View.ContactEmail = View.Email.Text;
            View.ContactCompanyId = ((CompanyListDto)View.Companies.SelectedItem).Id;
        }
        private void ToggleButtons()
        {
            Contact contact = GetContactFromUI();
            bool b = ViewDirtyFlag;
            View.Apply.IsEnabled = b && contact.IsValid;
            View.Cancel.IsEnabled = b;
        }
        public bool ViewDirtyFlag
        {
            get
            {
                bool companyChanged = View.Companies.SelectedItem == null ? false : ((CompanyListDto)View.Companies.SelectedItem).Id != View.ContactCompanyId;
                return (View.ContactLastName != null)
                    && (
                        (View.ContactFirstName != View.FirstName.Text)
                        || (View.ContactLastName != View.LastName.Text)
                        || (View.ContactPhone != View.Phone.Text)
                        || (View.ContactEmail != View.Email.Text)
                        || (companyChanged)
                    );
            }
        }
        public void FillUI(Contact contact, IEnumerable<CompanyListDto> companies)
        {
            View.ContactId = contact.Id;
            View.ContactFirstName = contact.FirstName ?? string.Empty;
            View.ContactLastName = contact.LastName;
            View.ContactEmail = contact.Email ?? string.Empty;
            View.ContactPhone = contact.Phone ?? string.Empty;
            View.ContactCompanyId = contact.CompanyId;

            View.LastName.Text = contact.LastName;
            View.FirstName.Text = contact.FirstName ?? string.Empty;
            View.Phone.Text = contact.Phone ?? string.Empty;
            View.Email.Text = contact.Email ?? string.Empty;

            if (companies != null)
            {
                View.Companies.Items.Clear();
                foreach (var company in companies)
                {
                    View.Companies.Items.Add(company);
                    if (company.Id == contact.CompanyId)
                    {
                        View.Companies.SelectedItem = company;
                    }
                }
            }
            ToggleButtons();
        }
        private void ChooseCompany(int companyId)
        {
            foreach (var item in View.Companies.Items)
            {
                CompanyListDto company = (CompanyListDto)item;
                if (company.Id == companyId)
                {
                    View.Companies.SelectedItem = item;
                }
            }
        }
        public Contact GetContactFromUI()
        {
            Contact contact = new Contact();
            contact.Id = View.ContactId;
            contact.LastName = View.LastName.Text;
            contact.FirstName = View.FirstName.Text;
            contact.Phone = View.Phone.Text;
            contact.Email = View.Email.Text;
            if (View.Companies.SelectedItem == null)
            {
                contact.CompanyId = 0;
            }
            else
            {
                contact.CompanyId = ((CompanyListDto)View.Companies.SelectedItem).Id;
            }
            return contact;
        }
    }
}
